package com.lntea.jdbc.spring;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import com.lntea.jdbc.spring.bean.GoodsStock;

@RunWith(SpringRunner.class)
@ContextConfiguration(locations={"classpath:com/lntea/jdbc/spring/jdbc-template.xml"})
public class NamedParameterJdbcTemplateTest {
	
	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	// SqlParameterSource接口支持名称参数的设置
	// 主要实现由两个：MapSqlParameterSource 和 BeanPropertySqlParameterSource 
	// 也可以直接使用Map设置
	
	// 1.MapSqlParameterSource, key-value的方式
	@Test
	public void testMapSqlParameterSource(){
		String sql = "select count(*) from t_wms_goods_stock where warehouse_id = :warehouse_id";
		SqlParameterSource namedParameters = new MapSqlParameterSource("warehouse_id", 1);
		Integer count = namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
		System.out.println("count:"+ count);
	}
	
	// 2.BeanPropertySqlParameterSource， 解析Bean的property
	@Test
	public void testBeanPropertySqlParameterSource(){
		GoodsStock gs = new GoodsStock();
		gs.setWarehouseId(1);
		
		String sql = "select count(*) from t_wms_goods_stock where warehouse_id = :warehouseId";
		SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(gs);
		Integer count = namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
		System.out.println("count:" + count);
	}
}
